from select import select
import socket
import struct
import time

TCPTHREADNUM=5
MYHOST=socket.gethostbyname(socket.gethostname())
PORTHEAD=7000

def startTCP(clientsocket):
    while True:
        dstSocket,dstAddr=clientsocket.accept()
        print("TCP: ",dstAddr)

def processPost():
    pass

def processHead(url,data):
    pass

if __name__=="__main__":
    tcpSocketArr=[socket.socket(socket.AF_INET,socket.SOCK_STREAM,socket.IPPROTO_IP) for i in range(TCPTHREADNUM)]
    for i in range(len(tcpSocketArr)):
        tcpSocketArr[i].bind((MYHOST,PORTHEAD+i))
        tcpSocketArr[i].listen(5)

    mainTcpsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM,socket.IPPROTO_IP)
    mainTcpsocket.bind((MYHOST,PORTHEAD-1))
    mainTcpsocket.listen(5)

    while True:
        try:
            readale,writeable,_=select([mainTcpsocket],[mainTcpsocket],[])
            for sk in readale:
                if(sk is mainTcpsocket):
                    clientSocket,_=sk.accept()
                    postData=''
                    firstPacket=clientSocket.recv(1024)
                    items=str(firstPacket,encoding="utf-8").split("\r\n")
                    postData+=items[-1]
                    requestLineItems=items[0].split(" ")
                    requestMethod=requestLineItems[0]
                    requestUrl=requestLineItems[1]
                    contentLength=0

                    for item in items:
                        if(item.startswith("Content-Length")):
                            contentLength=int(item.split(":")[1])
                    while(len(postData)<contentLength):
                        packet=clientSocket.recv(1024)
                        postData+=str(packet,encoding="utf-8")
                    if(requestMethod=="POST"):
                        processPost(requestUrl,postData)
                    elif(requestMethod=="HEAD"):
                        processHead()
                    #elif(requestMethod=="GET"):

                    stateLine="HTTP/1.0 200 OK\r\n"

                    header="Date: Tue, 09 Nov 2021 21:28:17 GMT\r\n\
                        Server: My Http Server\r\n\
                        Content-Type: text/html\r\n\
                        Content-Length: 12225\r\n\
                        Last-Modified: Wed, 27 Jun 2007 16:07:00 GMT\r\n"
                    endline="\r\n"

                    ROOT="./root"
                    if(requestUrl=="/"):
                        requestUrl="/index.html"
                    with open(ROOT+requestUrl,"rb") as f:
                        clientSocket.send(bytes(stateLine+header+endline,encoding="utf-8")+f.read())

            clientSocket.close()
        except Exception as e:
            print(e)